import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_hkzf/routers.dart';
import 'package:flutter_hkzf/scoped_model/auth.dart';
import 'package:flutter_hkzf/utils/common_toast.dart';
import 'package:flutter_hkzf/utils/dio_http.dart';
import 'package:flutter_hkzf/utils/scopoed_model_helper.dart';
import 'package:flutter_hkzf/utils/store.dart';
import 'package:flutter_hkzf/utils/string_is_null_or_empty.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key? key}) : super(key: key);

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  bool showPassword = false;
  var usernameController = TextEditingController();
  var passwordController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text("登录")),
      body: SingleChildScrollView(
          child: Padding(
              padding: const EdgeInsets.all(20),
              child: Column(
                children: [
                  TextField(
                    controller: usernameController,
                    decoration: const InputDecoration(
                        labelText: '账号', hintText: "请输入用户名"),
                  ),
                  TextField(
                    controller: passwordController,
                    obscureText: !showPassword,
                    decoration: InputDecoration(
                      labelText: '密码',
                      hintText: "请输入密码",
                      suffixIcon: IconButton(
                        icon: Icon(showPassword
                            ? Icons.visibility_off
                            : Icons.visibility),
                        onPressed: () {
                          //todo:改变事件
                          setState(() {
                            showPassword = !showPassword;
                          });
                        },
                      ),
                    ),
                  ),
                  const SizedBox(height: 20),
                  Container(
                    width: double.infinity,
                    height: 40,
                    child: ElevatedButton(
                      child: const Text(
                        "登录",
                        style: TextStyle(fontSize: 26),
                      ),
                      onPressed: () {
                        _loginHandle();
                      },
                    ),
                  ),
                  const SizedBox(
                    height: 16,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const Text("还没有账号"),
                      const SizedBox(height: 20),
                      TextButton(
                          onPressed: () {
                            Navigator.pushReplacementNamed(context, 'register');
                          },
                          child: const Text("去注册",
                              style: TextStyle(color: Colors.teal)))
                    ],
                  )
                ],
              ))),
    );
  }

  void _loginHandle() async {
    var userName = usernameController.text;
    var passWord = passwordController.text;
    if (stringIsNullOrEmpty(userName) || stringIsNullOrEmpty(passWord)) {
      CommonToast.showToast('用户名或密码不能为空!');
      return;
    }
    const url = "/login";
    var params = {'username': userName, 'password': passWord};
    var res = await DioHttp.of(context).post(url, params);
    var resMap = json.decode(res.toString());
    print(resMap);

    bool success = resMap['success'];
    String description = resMap['msg'] ?? '内部错误';
    CommonToast.showToast(description);
    if (success) {
      String token = resMap['token'];
      //bug:缓存
      Store store = await Store.getInstance();
      await store.setString(StoreKeys.token, token);
      //全局管理状态
      ScopedModelHelper.getModel<AuthModel>(context).login(token, context);
      Timer(const Duration(seconds: 1), () {
        Navigator.of(context).pop();
      });
    }
    //返回上一页
    // Navigator.of(context).pop();
  }
}
